import React, {PureComponent} from 'react';
import {connect} from 'dva';
import {
    Row,
    Col,
    Card,
    Form,
    Input,
    Select,
    Button,
    Modal,
    message
} from 'antd';
import PageHeaderLayout from "../../../layouts/PageHeaderLayout";
import PaymentConfigruationList from "../../../components/Payment/paymentConfigruation/PaymentConfigruationList";
import PaymentConfigruationAdd from "../../../components/Payment/paymentConfigruation/PaymentConfigruationAdd";
import styles from './PaymentConfigruation.less';
import {powerControl} from '../../../utils/powerControl';
const AuthButton = powerControl(Button);

const FormItem=Form.Item;
const {Option} = Select;
const getValue = obj => Object.keys(obj).map(key => obj[key]).join(',');
@connect(state => ({
    rule: state.paymentConfigruation
}))
@Form.create()
export default class PaymentConfigruation extends PureComponent{
    state = {
        modalVisible: false,
        editType: 'add',
        formValues: {},
        record: {},
        selectedRows: [],
    };

    componentDidMount(){
        const {dispatch} = this.props;
        dispatch({
           type: 'paymentConfigruation/fetch',
        });
    }

    /**
     * 重置查询
     */
    handleFormReset = () => {
        const {form, dispatch} = this.props;
        form.resetFields();
        dispatch({
            type: 'paymentConfigruation/fetch',
            payload: {},
        });
        this.setState({
            formValues: {},
        })
    };

    /**
     * 打开新增支付配置modal
     */
    handleAddPayment = () => {
        this.handleModalVisible(true);
        this.setState({
            editType: 'add',
        });
    }

    /**
     * 新增支付配置
     */
    handleAdd = () =>{
        this.props.dispatch({
            type: 'paymentConfigruation/add',
            payload: {
              description: this.state.addInputValue,
            },
        });

        message.success('添加成功');
        this.setState({
            modalVisible:false,
        });
    };

    /**
     * 改变modal状态
     * @param flag
     */
    handleModalVisible = (flag) => {
        this.setState({
            modalVisible: !!flag,
        });
    };

    /**
     * 新增成功重新查询列表
     * @param pagination
     */
    handleModalSuccess = (pagination) => {
        const {dispatch} = this.props;
        const {formValues} = this.state;
        const params = {
            currentPage: pagination.current,
            pageSize: pagination.pageSize,
            ...formValues,
        };
        dispatch({
            type: 'paymentConfigruation/fetch',
            payload: params,
        });
    };

    /**
     * 查询
     * @param e
     */
    handleSearch = (e) => {
        e.preventDefault();

        const {dispatch, form} = this.props;

        form.validateFields((err, fieldsValue) => {
            if (err){
                return;
            }
            const values = {
                ...fieldsValue,
                updatedAt: fieldsValue.updatedAt && fieldsValue.updatedAt.valueOf(),
            };

            this.setState({
               formValues: values,
            });

            dispatch({
                type: 'paymentConfigruation/fetch',
                payload: values,
            })
        });
    };

    handleSelectRows = (rows) =>{
        this.setState({
            selectedRows:rows,
        });
    };

    /**
     * 翻页
     **/
    handleConfigruationListChange = (pagination, filtersArg, sorter) =>{
        const {dispatch} = this.props;
        const {formVales} = this.state;

        const filters = Object.keys(filtersArg).reduce((obj, key) =>{
            const newObj = {...obj};
            newObj[key] = getValue(filtersArg[key]);
            return newObj;
        }, {});

        const params = {
            currentPage: pagination.current,
            pageSize: pagination.pageSize,
            ...formVales,
            ...filters,
        };

        if (sorter.field){
            params.sorter = `${sorter.field}_${sorter.order}`;
        }

        dispatch({
            type: 'paymentConfigruation/fetch',
            payload: params,
        });
    }

    /**
     * 删除表格中的某一行
     **/
    handleDelConfigruationRow = (pay_id, pagination) => {
        const {dispatch} = this.props;
        dispatch({
            type: 'paymentConfigruation/del',
            payload: {pay_id: pay_id},
            callback: (response) => {
                if (response.result === 0){
                    message.success('删除成功');
                    this.handleModalSuccess(pagination)
                }else {
                    message.success('删除失败');
                }
            }

        });
    };

    /**
     * 编辑表格中的mou
     **/
    handleEditConfigruationRow = (record, pagination) =>{
        this.handleModalVisible(true);
        this.setState({
            editType: 'mod',
            record: record,
        });
    };

    renderSimpleForm(){
        const {getFieldDecorator} = this.props.form;
        return(
            <Form layout= "inline" onSubmit={this.handleSearch}>
                <Row gutter = {{md: 8, lg: 24, xl: 48}}>
                    <Col md = {8} sm = {24}>
                        <FormItem label = "支付方式编码">
                            {getFieldDecorator('pay_code')(
                                <Input placeholder = "请输入"/>
                            )}
                        </FormItem>
                    </Col>
                    <Col md={8} sm={24}>
                        <FormItem label = "是否可用">
                            {getFieldDecorator('enabled')(
                                <Select
                                    placeholder = "请选择"
                                    style = {{width:'100%'}}>
                                    <Option value = "">请选择</Option>
                                    <Option value = "1">可用</Option>
                                    <Option value = "0">不可用</Option>
                                </Select>
                            )}
                        </FormItem>
                    </Col>
                    <Col
                        md = {8}
                        sm = {24}>
                        <span className={styles.sumbitButtons}>
                            <AuthButton auth="paymentConfigruation.search" type = "primary" htmlType = "submit">
                                查询
                            </AuthButton>
                            <AuthButton auth="paymentConfigruation.reset" style={{marginLeft: 8}} onClick={this.handleFormReset}>
                                重置
                            </AuthButton>
                        </span>
                    </Col>
                </Row>
            </Form>
        );
    }

    renderForm() {
        return this.renderSimpleForm();
    }

    render(){
        const {modalVisible, editType, record, selectedRows} = this.state;
        const {rule: {loading: ruleLoading, data, paymentConfigruationList}} = this.props;
        return(
            <PageHeaderLayout title = "支付配置管理">
                <Card bordered = {false}>
                    <div className={styles.tableList}>
                        <div className={styles.tableListForm}>
                            {this.renderForm()}
                        </div>
                        <div className={styles.tableListOperator}>
                            <AuthButton auth="paymentConfigruation.new" type = "primary" icon = "plus" onClick={() => this.handleAddPayment()}>
                                新建
                            </AuthButton>
                            <PaymentConfigruationList
                                selectedRows={selectedRows}
                                loading={ruleLoading}
                                data={data}
                                onSelectRow={this.handleSelectRows}
                                onChange={this.handleConfigruationListChange}
                                onDelRow={this.handleDelConfigruationRow}
                                onEditRow={this.handleEditConfigruationRow}
                            />
                        </div>
                    </div>
                </Card>
                <Modal
                    title = "新增支付配置 "
                    visible = {modalVisible}
                    onOk = {this.handleAdd}
                    onCancel = {() => this.handleModalVisible()}
                    footer = {null}
                    key = {new Date()}
                >
                    <PaymentConfigruationAdd
                        ref = "paymentConfigruationAdd"
                        pagination = {data.pagination}
                        editType={editType}
                        record={record}
                        categorySList={paymentConfigruationList}
                        handleModalVisible={this.handleModalVisible}
                        handleModalSuccess={this.handleModalSuccess}/>
                </Modal>
            </PageHeaderLayout>
        );
    }
}
